package com.bsoft.gol.hcs.visitrecord.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.atag.dao.ext.HibernateExtendDAO;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.utils.CommonUtils;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.model.SimplePageInfo;
import com.bsoft.gol.hcs.visitrecord.bean.qo.HospitalVisitsRecordListQo;
import com.bsoft.gol.hcs.visitrecord.bean.qo.InspectionReportRecordsReq;
import com.bsoft.gol.hcs.visitrecord.bean.vo.ApplicationFormRecordVo;
import com.bsoft.gol.hcs.visitrecord.bean.vo.HospitalVisitsRecordListVo;
import com.bsoft.gol.hcs.visitrecord.entity.VrApplicationFormRecord;

import java.util.*;

/**
 * Created by ChenJij on 2020/9/4.
 */
public abstract class VrApplicationFormRecordDAO extends HibernateExtendDAO<VrApplicationFormRecord> {
    public VrApplicationFormRecordDAO() {
        this.setKeyField("applicationId");
    }

    /**
     * @description: 更新满意度调查已完成数量
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/9 13:25
     */
    @DAOMethod(sql = "update VrApplicationFormRecord set finishNumber=finishNumber+1 where  applicationId=:businessId")
    public abstract void updateFinishNumber(@DAOParam("businessId") String businessId);

    /**
     * 根据日期查询记录
     *
     * @param resultDate
     * @return
     */
    @DAOMethod(sql = "from VrApplicationFormRecord where application_time <:resultDate and delete_flag !='1' ")
    public abstract List<VrApplicationFormRecord> queryApplicationFormRecordList(@DAOParam("resultDate") Date resultDate);

    /**
     * 更新删除标识
     */
    @DAOMethod(sql = "update VrApplicationFormRecord set delete_flag='1' where business_id in(:businessIdList)")
    public abstract void updateDeleteFlag(@DAOParam("businessIdList") List<String> businessIdList);

    /**
     * 查询所有的病人id
     *
     * @return java.util.List<java.lang.String>
     * @throws
     * @author tongtp
     * @date 2022/6/14 15:15
     */
    public List<String> queryAllPatientId(final String categoryCode, final List<String> departmentIds) {
        HibernateStatelessResultAction<List<String>> action =
                new AbstractHibernateStatelessResultAction<List<String>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT DISTINCT patient_id AS patientId ");
                        sqlBuilder.append(" FROM vr_application_form_record ");
                        sqlBuilder.append(" WHERE patient_id is not null ");
                        sqlBuilder.append(" AND bill_category_code=:categoryCode ");
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            sqlBuilder.append(" and department_id in (:departmentIds) ");
                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        query.setParameter("categoryCode", categoryCode);
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            query.setParameterList("departmentIds", departmentIds);
                        }
                        List list = query.list();
                        List<String> voList;
                        if (CommonUtils.isNotEmpty(list)) {
                            voList = list;
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 根据患者id获取最新的一条数据
     */
    public VrApplicationFormRecord getPatientIdAndLastOne(String patientId, String categoryCode, String departmentId) {
        HibernateStatelessResultAction<VrApplicationFormRecord> action =
                new AbstractHibernateStatelessResultAction<VrApplicationFormRecord>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        List departmentIds = null;
                        if (CommonUtils.isNotNull(departmentId)) {
                            departmentIds = Arrays.asList(departmentId.split(","));
                        }
                        StringBuilder builder = new StringBuilder();
                        builder.append(" from VrApplicationFormRecord  where  patientId =:patientId AND billCategoryCode=:categoryCode ");
                        builder.append(" and applicationTime is not null");
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            builder.append(" and departmentId in (:departmentIds) ");
                        }
                        builder.append(" order by applicationTime desc");
                        Query query = ss.createQuery(builder.toString());
                        query.setParameter("patientId", patientId);
                        query.setParameter("categoryCode", categoryCode);
                        if (CommonUtils.isNotEmpty(departmentIds)) {
                            query.setParameterList("departmentIds", departmentIds);
                        }
                        // 查询的条数
                        query.setMaxResults(1);
                        // 开始查询的位置
                        query.setFirstResult(0);
                        List<Map<String, Object>> dbList = query.list();
                        if (CommonUtils.isNotEmpty(dbList)) {
                            setResult(ConversionUtils.convert(dbList.get(0), VrApplicationFormRecord.class));
                        } else {
                            setResult(null);
                        }
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();

    }

    @DAOMethod(sql = " from VrApplicationFormRecord where applicationNo =:applicationNo and organizationId=:organizationId")
    public abstract VrApplicationFormRecord getVrApplicationFormRecord(@DAOParam("applicationNo") String applicationNo, @DAOParam("organizationId") String organizationId);

    public SimplePageInfo<HospitalVisitsRecordListVo> queryOutpatientVisitRecordList(HospitalVisitsRecordListQo qo, String groupConcatType) {
        QoHibernateStatelessResultAction<HospitalVisitsRecordListVo, HospitalVisitsRecordListQo> action = new QoHibernateStatelessResultAction(true, qo, HospitalVisitsRecordListVo.class);
        action.setSql(" SELECT {{" +
                " '" + qo.getBusinessType() + "' businessType, " +
                " c.application_id AS businessId, " +
                " organization_id AS organizationId, " +
                " patient_id AS patientId, " +
                " c.patient_name AS patientName, " +
                " c.patient_sex AS patientSex, " +
                " c.patient_age_text AS patientAge, " +
                " c.open_department_name AS departmentName, " +
                " c.survey_number AS surveyNumber, " +
                " c.finish_number AS finishNumber, " +
                " c.patient_medical_card_number AS patientMedicalCardNumber, " +
                " c.patient_medical_card_type AS patientMedicalCardType, " +
                " c.card_number AS cardNumber, " +
                " c.card_type AS cardType, " +
                " c.telephone, " +
                " c.open_doctor_name AS doctorName, " +
                " c.executive_time AS executiveTime, " +
                " c.open_time AS openTime,d.itemName }}" +
                "FROM " +
                " vr_application_form_record c, " +
                " ( " +
                "  SELECT " +
                "   b.application_id, " +
                "   " + groupConcatType + "(b.item_name) itemName " +
                "  FROM " +
                "   vr_application_form_record a, " +
                "   vr_application_form_detail b " +
                "  WHERE " +
                "   a.application_id = b.application_id ");
        action.addCondition("  AND b.item_id =:itemId ");
        action.addSql("  GROUP BY " +
                "   b.application_id " +
                " ) d " +
                "WHERE " +
                " c.application_id = d.application_id  ");
        action.addCondition(" and c.bill_category_code =:billCategoryCode ");
        action.addCondition(" and c.patient_name =:patientName ");
        action.addCondition(" and c.telephone =:telephone ");
        action.addCondition(" and c.patient_medical_card_number =:patientMedicalCardNumber ");
        action.addCondition(" and c.organization_id =:organizationId ");
        action.addCondition(" and c.open_department_id =:departmentId ");
        action.addCondition(" and c.open_doctor_id =:doctorId ");
        if ("1".equals(qo.getDateType())) {
            action.addCondition(" and open_time >=:beginDate ");
            action.addCondition(" and open_time <:endDate ");
        } else if ("2".equals(qo.getDateType())) {
            action.addCondition(" and executive_time >=:beginDate ");
            action.addCondition(" and executive_time <:endDate ");
        } else if ("3".equals(qo.getDateType())) {
            action.addCondition(" and report_time >=:beginDate ");
            action.addCondition(" and report_time <:endDate ");
        }

        HibernateSessionTemplate.instance().execute(action);
        SimplePageInfo<HospitalVisitsRecordListVo> pageInfo = action.getSimpleResultPage();
        return pageInfo;
    }


    public List<ApplicationFormRecordVo> queryInspectionReportRecords(final InspectionReportRecordsReq reportRecordsReq) {
        HibernateStatelessResultAction<List<ApplicationFormRecordVo>> action =
                new AbstractHibernateStatelessResultAction<List<ApplicationFormRecordVo>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT application_id applicationId,application_no applicationNo,application_time applicationTime," +
                                "applicant applicant,bill_category_code billCategoryCode,application_form_status applicationFormStatus," +
                                "patient_type patientType,patient_nature patientNature,patient_id patientId,patient_name patientName," +
                                "patient_sex patientSex,patient_birthday patientBirthday,patient_age patientAge,age_unit ageUnit," +
                                "card_type cardType,card_number cardNumber,patient_medical_card_type patientMedicalCardType," +
                                "patient_medical_card_number patientMedicalCardNumber,telephone telephone,address address," +
                                "section section,bed_number bedNumber,organization_id organizationId,organization_name organizationName," +
                                "open_time openTime,open_doctor_id openDoctorId,open_doctor_name openDoctorName," +
                                "open_department_id openDepartmentId,open_department_name openDepartmentName,emergency_mode emergencyMode," +
                                "amount amount,executive_time executiveTime,executive_doctor_id executiveDoctorId," +
                                "executive_doctor_name executiveDoctorName,executive_department_id executiveDepartmentId," +
                                "executive_department_name executiveDepartmentName,audit_time auditTime,audit_doctor_id auditDoctorId," +
                                "audit_doctor_name auditDoctorName,report_time reportTime,report_doctor_id reportDoctorId," +
                                "report_doctor_name reportDoctorName,cancel_doctor_id cancelDoctorId,cancel_doctor_name cancelDoctorName," +
                                "cancel_time cancelTime,invoice_number invoiceNumber,satisfaction_status satisfactionStatus," +
                                "survey_number surveyNumber,finish_number finishNumber,companion_name companionName," +
                                "companion_relationship companionRelationship,companion_phone companionPhone," +
                                "patient_age_text patientAgeText FROM `vr_application_form_record` where  1=1 ");
                        //查询类型，参数设置，1表示按患者患者标识集合查询；2表示按证件集合查询；3表示按诊疗卡集合查询；
                        switch (reportRecordsReq.getQueryType()) {
                            case "1":
                                sqlBuilder.append("AND patient_id=:patientId ");
                                break;
                            case "2":
                                sqlBuilder.append("AND card_type=:cardType AND card_number=:cardNumber ");
                                break;
                            case "3":
                                sqlBuilder.append("AND patient_medical_card_type=:patientMedicalCardType AND patient_medical_card_number=:patientMedicalCardNumber ");
                                break;
                            default:
                                break;
                        }
                        if (!"0".equals(reportRecordsReq.getBillCategoryCode())) {
                            sqlBuilder.append("AND bill_category_code=:billCategoryCode ");

                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        switch (reportRecordsReq.getQueryType()) {
                            case "1":
                                query.setParameter("patientId", reportRecordsReq.getPatientId());
                                break;
                            case "2":
                                query.setParameter("cardType", reportRecordsReq.getCardType());
                                query.setParameter("cardNumber", reportRecordsReq.getCardNumber());
                                break;
                            case "3":
                                query.setParameter("patientMedicalCardType", reportRecordsReq.getPatientMedicalCardType());
                                query.setParameter("patientMedicalCardNumber", reportRecordsReq.getPatientMedicalCardNumber());
                                break;
                            default:
                                break;
                        }
                        if (!"0".equals(reportRecordsReq.getBillCategoryCode())) {
                            query.setParameter("billCategoryCode", reportRecordsReq.getBillCategoryCode());

                        }
                        query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                        List<Map> dbList = query.list();
                        setResult(mapToList(dbList));
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private List<ApplicationFormRecordVo> mapToList(List<Map> maps) {
        List<ApplicationFormRecordVo> feedbackList = new ArrayList<>();
        for (Map map : maps) {
            feedbackList.add(ConversionUtils.convert(map, ApplicationFormRecordVo.class));
        }
        return feedbackList;
    }
}